<template>
  <div>
    <div @click="openSelection" class="person-select-view" :class="disabled?'disabled':''">
      <div v-if="!persons || persons.length===0" class="placeholder">{{ placeholder }}</div>

      <div v-for="(person,index) in persons" v-if=" multiple && index<maxShow" class="user-select-item" @click.stop>
        {{ person.name }}
        <i v-if="!disabled" @click.stop="deletePerson(person,index)" class="select-user-remove el-icon-close"></i>
      </div>
      <div v-if="!multiple&&persons.length>0">
        <span style="margin: 5px">{{ persons[0].name }}</span>
      </div>
      <div @mouseleave="moreHover=false">
        <div v-if=" persons.length>maxShow" class="user-select-more"
             @mouseenter="moreHover=true">+{{ persons.length - maxShow }}人
        </div>
        <div class="more-users" v-if="moreUsers">
          <div v-for="(person,index) in persons" v-if="index>=maxShow" class="user-select-item" @click.stop>
            {{ person.name }}
            <i v-if="!disabled" @click.stop="deletePerson(person,index)" class="select-user-remove el-icon-close"></i>
          </div>
        </div>
      </div>
    </div>
    <i v-if="!disabled && value" class="el-icon-circle-close clear-users" @click="clearPerson"></i>
    <el-dialog :visible.sync="dialogVisible" @close="onClose" append-to-body width="1000px" top="10px !important">
      <el-row :gutter="20">
        <!--部门数据-->
        <el-col :span="5" :xs="24">
          <div class="head-container">
            <el-input
                v-model="deptName"
                placeholder="请输入部门名称"
                clearable
                size="small"
                prefix-icon="el-icon-search"
                style="margin-bottom: 20px"
            />
          </div>
          <div class="tree-container ">
            <div class="tree">
              <el-tree
                  :data="deptOptions"
                  :props="defaultProps"
                  node-key="id"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  :default-expanded-keys="defaultExpand"
                  ref="tree"
                  @node-click="handleNodeClick"
              >
                <template #default="scope">
                <span class="el-tree-node__label" :title="scope.node.label">
                  <slot :row="scope">
                    {{ scope.node.label }}
                  </slot>
                </span>
                </template>
              </el-tree>
            </div>
          </div>
        </el-col>
        <!--用户数据-->
        <el-col :span="19" :xs="24">
          <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="用户名称" prop="userName">
              <el-input
                  v-model="queryParams.name"
                  placeholder="请输入用户名称"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                  v-model="queryParams.phonenumber"
                  placeholder="请输入手机号码"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-row :gutter="10" class="mb8">
            <div class="person-select-view">
              <div v-if="!selected&&selected.length===0" style="color: #dcdcdc">未选择...</div>
              <div v-for="(user,index) in selected" class="user-select-item" @click.stop>
                {{ user.name }}
                <i @click.stop="deleteSelect(user,index)" class="select-user-remove el-icon-close"></i>
              </div>
            </div>
          </el-row>
          <el-table ref="personTable"
                    v-loading="loading"
                    :data="personList"
                    :height="450"
                    :highlight-current-row="!multiple"
                    @current-change="handleCurrentChange"
                    @selection-change="handleSelectionChange">
            <el-table-column v-if="multiple" type="selection" width="50" align="center"/>
            <el-table-column label="姓名" align="center" prop="name" width="120"
                             :show-overflow-tooltip="true"/>
            <el-table-column label="工号" align="center" prop="code" width="100"
                             :show-overflow-tooltip="true"/>
            <el-table-column label="部门" align="center" prop="orgName"
                             :show-overflow-tooltip="true"/>
            <el-table-column label="电话" align="center" prop="phonenumber" width="130"/>
          </el-table>
          <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
          />
        </el-col>
      </el-row>
      <template v-slot:footer>
        <el-button type="primary" size="small" @click="submit"> 确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {treeselect} from "@/api/system/dept";
import {listPerson, listPersonByIds} from "@/api/business/person";

export default {
  name: 'PersonSelect',
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    value: [String, Number],
    multiple: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: "请选择人员"
    },
    maxShow: {
      type: Number,
      default: 5
    },
    showMore: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    moreUsers() {
      return this.showMore && this.selected.length > this.maxShow && this.moreHover
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(newVal, oldVal) {
        this.initData()
      }
    },
    persons(val) {
      this.selected = val;
    }
  },
  emits: ['input', 'change'],
  data() {
    return {
      persons: [],
      // 遮罩层
      loading: true,
      showSearch: true,
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      // 总条数
      total: 0,
      // 用户表格数据,
      genderOptions: [],
      //默认展开
      defaultExpand: [],
      personList: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      dialogVisible: false,
      queryParams: {},
      selected: [],
      moreHover: false
    }
  },
  methods: {
    openSelection() {
      if (this.disabled) {
        return
      }
      this.getTreeselect();
      this.getList();
      this.dialogVisible = true;
    },
    initData() {
      listPersonByIds(this.value).then(response => {
        this.persons = response.data
      })
    },
    /** 查询用户列表 */
    async getList() {
      this.loading = true;
      await listPerson(this.addDateRange(this.queryParams, this.dateRange))
          .then(response => {
            this.personList = response.rows;
            this.total = response.total;
            this.loading = false;
            return response.rows;
          }).then(() => {
            if (this.value) {
              const personIdArray = this.value.split(",").map(item => Number(item));
              this.personList.forEach(person => {
                if (personIdArray.includes(person.id)) {
                  this.$refs.personTable.toggleRowSelection(person, true);
                }
              })
            }
          })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if (!this.dialogVisible) {
        return
      }
      this.selected = selection;
    },
    // 点击选中数据
    handleCurrentChange(current) {
      if (current == null || this.multiple || !this.dialogVisible) {
        return
      }
      this.selected = [current]
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        const orgTree = response.data
        if (orgTree) {
          orgTree.forEach(item => {
            this.defaultExpand.push(item.id);
            if (item.children) {
              item.children.forEach(item2 => {
                this.defaultExpand.push(item2.id);
              })
            }
          })
        }
        this.deptOptions = orgTree;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.orgid = data.id;
      this.getList();
    },
    deleteSelect(item, index) {
      this.selected.splice(index, 1);
      this.$refs.personTable.toggleRowSelection(item, false)
    },
    deletePerson(item, index) {
      this.persons.splice(index, 1);
      this.emit();
    },
    clearPerson() {
      this.selected = [];
      this.emit();
    },
    emit() {
      const userId = this.selected.map(item => item.id).join(',');
      this.$emit('input', userId);
      this.$emit('change', this.selected);
    },
    // 性别字典翻译
    genderFormat(row, column) {
      return this.selectDictLabel(this.genderOptions, row.gender);
    },
    submit() {
      this.persons = JSON.parse(JSON.stringify(this.selected));
      this.emit();
      this.selected = []
      this.dialogVisible = false;
    },
    onClose() {
      this.selected = []
    }
  }

}
</script>

<style scoped lang="scss">

.placeholder {
  margin: 0 10px;
  color: #c0c4cc;
}

.person-select-view {
  &.disabled {
    background: #f6f6f6;
  }

  width: 100%;
  height: 38px;
  padding: 3px 20px 3px 3px;
  border-radius: 3px;
  border: #dce2ea 1px solid;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-content: center;
  justify-content: flex-start;
  align-items: center;
}

.user-select-item {
  margin: 5px;
  height: 20px;
  padding: 3px;
  border-radius: 3px;
  border: #e1e1e1 solid 1px;
  background: #e5e5e5;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: row;
  flex-wrap: nowrap;
  color: #888888;
  font-size: 12px;

  .select-user-remove {
    margin-left: 3px;
    background: #c1c1c1;
    width: 12px;
    height: 12px;
    font-size: 10px;
    border-radius: 50%;
    text-align: center;
    padding-top: 1px;
    color: grey;

    &:hover {
      background: #707070;
      color: #ffffff;
    }
  }
}

.user-select-more {
  margin: 5px;
  height: 20px;
  padding: 3px;
  border-radius: 3px;
  border: #e1e1e1 solid 1px;
  background: #e5e5e5;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: row;
  flex-wrap: nowrap;
  color: #888888;
  font-size: 12px;
}

.tree-container {
  overflow: auto;
  height: 550px;

  .tree {
    display: flex;
  }
}

.more-users {
  background: white;
  min-height: 80px;
  min-width: 100px;
  max-height: 300px;
  max-width: 500px;
  z-index: 999;
  display: flex;
  float: left;
  position: fixed;
  border: 1px #bfbfbf solid;
  border-radius: 2px;
}

.clear-users {
  position: relative;
  float: right;
  top: -26px;
  right: 5px;
  color: #777777;
}

::v-deep .el-dialog__body {
  padding: 10px;
}
</style>
